/**
 * The program is aimed to auto-move mlfs from BuildFile_complete to
 * AutoPack\Collection_out according to corresponding model number.
 * 
 * @author Jamie Chien
 * @version 1.0
 */
package com.fihtdc.mlfmover;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class MlfMover {
    private static boolean DEBUG = false;

    /**
     * @param args
     *            location of collection.conf, daily build version, location
     *            where mlf will move to
     */
    public static void main(String args[]) {
        try {
            @SuppressWarnings("unused")
            MlfMover mMover = new MlfMover(args[0], args[1], args[2]);

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Must follow with three parameters:\n"
                    + "$1:collection.conf location\n" + "$2:build version\n"
                    + "$3:AutoPack Collection_out location");
            // e.printStackTrace();
        }
    }

    private final File                CONF_FILE;
    private final String              VERSION;
    private final String              DEST;
    private String                    NAME;
    private final ArrayList<String[]> model_list;
    private String                    PROJECT;
    private String                    MODEL;

    private String                    IMAGE_TYPE;

    private final File                LOG;

    /**
     * @param path
     *            location of collection.conf
     * @param ver
     *            build version
     * @param dest
     *            location where mlfs will move to
     */
    public MlfMover(String path, String ver, String dest) {
        CONF_FILE = new File(path);
        VERSION = ver;
        DEST = dest;
        String tmp;
        model_list = new ArrayList<String[]>();
        File srcFile;
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LOG = new File(CONF_FILE.getParent() + "/" + "MoveMlf_" + sdf.format(cal.getTime())
                + ".log");

        try {
            FileWriter fw = new FileWriter(LOG);
            fw.write(sdf.format(cal.getTime()) + "\n");
            int size = 0;
            // read in collection.conf
            BufferedReader br = new BufferedReader(new FileReader(CONF_FILE));
            while ((tmp = br.readLine()) != null && !"".equals(tmp.trim())) {
                PROJECT = tmp.split(" ")[0].split("=")[1];
                MODEL = tmp.split(" ")[1].split("=")[1];
                IMAGE_TYPE = tmp.split(" ")[2].split("=")[1];
                model_list.add(size, new String[] { PROJECT, MODEL, IMAGE_TYPE });
                NAME = PROJECT + "-" + VERSION + "-0-" + MODEL + "-A01.mlf";
                printDebug(size + " | " + NAME);

                size++;
            }
            br.close();
            printDebug("\n");

            // if (new File(CONF_FILE.getParent() + "/" + PROJECT
            // + "-VV-0-MM-A01.mlf").exists()) {
            // System.out.println("ERROR: mlf not generated!");
            // fw.write("ERROR: mlf not generated!\n");
            // fw.close();
            // System.exit(0);
            // }
            String name;
            for (int i = 0; i < model_list.size(); i++) {
                name = model_list.get(i)[0] + "-" + VERSION + "-0-" + model_list.get(i)[1]
                        + "-A01.mlf";
                printDebug("check " + CONF_FILE.getParent() + "/" + name);
                fw.write("check " + CONF_FILE.getParent() + "/" + name + "\n");

                // if mlf exists, copy to AutoPack/Collection_out/PROJECT_CODE
                srcFile = new File(CONF_FILE.getParent() + "/" + name);
                if (srcFile.exists()) {
                    if (new File(DEST + "/" + model_list.get(i)[1]).exists()) {
                        printDebug("yes, copy to " + DEST + "/" + model_list.get(i)[1]);
                        fw.write("yes, copy to " + DEST + "/" + model_list.get(i)[1] + "\n");
                        copyToOut(fw, srcFile, new File(DEST + "/" + model_list.get(i)[1] + "/"
                                + name));
                    } else if (new File(DEST + "/" + model_list.get(i)[1] + "_someFileMissing")
                            .exists()) {
                        System.out.println("ERROR:" + model_list.get(i)[1] + " miss some file");
                        fw.write("ERROR:" + model_list.get(i)[1] + " miss some file\n");
                    } else {
                        System.out.println("ERROR:" + DEST + "/" + model_list.get(i)[1]
                                + " not exist!");
                        fw.write("ERROR:" + DEST + "/" + model_list.get(i)[1] + " not exist!\n");
                    }
                } else {
                    System.out.println("ERROR:" + srcFile + " not exist!");
                    fw.write("ERROR:" + srcFile + " not exist!\n");
                }
            }
            fw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void copyToOut(FileWriter fw, File srcFile, File dstFile) {
        printDebug("start copy " + srcFile.toString() + " to " + dstFile.toString());
        try {
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(dstFile);
            byte[] buff = new byte[1024];
            int len;
            while ((len = fis.read(buff)) > 0) {
                fos.write(buff, 0, len);
            }
            fis.close();
            fos.close();
            if (dstFile.exists()) {
                printDebug("copy done!");
                fw.write("copy done!\n");
            } else {
                System.out.println(dstFile + " copy fail!");
                fw.write(dstFile + " copy fail!\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void printDebug(String str) {
        if (DEBUG) {
            System.out.println(str);
        }
    }

}
